package com.ljfiction.book.http;

import android.content.Context;
import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.ljfiction.book.activitys.MyApication;


import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * volley的get/post请求
 */
public class VolleyRequestUtil {
    /*public static StringRequest stringRequest;
    public static Context context;


    public static void userAgent() throws IOException {
        //请求头
        String property = System.getProperty("http.agent");
        String path = "www.baidu.com";

        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("http.agent", property + " JYC_App_1.0.0_android");
    }


    *//*
    * 获取GET请求内容
    * 参数：
    * context：当前上下文；
    * url：请求的url地址；
    * tag：当前请求的标签；
    * volleyListenerInterface：VolleyListenerInterface接口；
    * *//*
    public static void RequestGet(String url, final Map<String, String> params, String tag, VolleyListenerInterface volleyListenerInterface) {
        // 清除请求队列中的tag标记请求
        MyApication.getRequestQueue().cancelAll(tag);
        // 创建当前的请求，获取字符串内容
        stringRequest = new StringRequest(Request.Method.GET, url, volleyListenerInterface.responseListener(), volleyListenerInterface.errorListener()) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = super.getHeaders();
                if (headers == null || headers.equals(Collections.emptyMap())) {
                    headers = new HashMap<String, String>();
                }
                String userAgent = System.getProperty("http.agent");
                if (!StringUtils.isSpace(userAgent)) {

                    headers.put("User-Agent", userAgent + " JYC_App_" + SystemToolUtils.getAppVersionName(AppManager.topActivity()) + "_" + "android");
                }
               *//* String cookie=PreferenceHelper.readString(PreferenceHelper.DEFAULT_FILE_NAME, AppConfig.PREFER_COOKIE_TAG, "");
                if(!TextUtils.isEmpty(cookie))
                {
                }*//*
               // MyLog.e("user-agent:" + headers.get("User-Agent") + "");
                return headers;
            }

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                params.put("access_token", PreferenceHelper.readString(PreferenceHelper.DEFAULT_FILE_NAME, AppConfig.PREFER_TOKEN_TAG, ""));
                params.put("appVersion",SystemToolUtils.getAppVersionName(AppManager.topActivity()));
                params.put("bundleID",SystemToolUtils.getAppPackageName(AppManager.topActivity()));
                return params;
            }
        };
        // 为当前请求添加标记
        stringRequest.setTag(tag);
        // 设置超时时间
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, 1.0f));
        // 将当前请求添加到请求队列中
        MyApication.getRequestQueue().add(stringRequest);
        // 重启当前请求队列
//        MyApication.getRequestQueue().start();
    }

    *//*
       * 获取GET请求内容
       * 参数：
       * context：当前上下文；
       * url：请求的url地址；
       * tag：当前请求的标签；
       * volleyListenerInterface：VolleyListenerInterface接口；
       * *//*
    public static void RequestGet(String url, String tag, VolleyListenerInterface volleyListenerInterface) {

        // 清除请求队列中的tag标记请求
        MyApication.getRequestQueue().cancelAll(tag);
        // 创建当前的请求，获取字符串内容
        stringRequest = new StringRequest(Request.Method.GET, url, volleyListenerInterface.responseListener(), volleyListenerInterface.errorListener()) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = super.getHeaders();
                if (headers == null || headers.equals(Collections.emptyMap())) {
                    headers = new HashMap<String, String>();
                }
                String userAgent = System.getProperty("http.agent");
                if (!StringUtils.isSpace(userAgent)) {

                    headers.put("User-Agent", userAgent + " JYC_App_" + SystemToolUtils.getAppVersionName(AppManager.topActivity()) + "_" + "android");
                }
              *//*  String cookie=PreferenceHelper.readString(PreferenceHelper.DEFAULT_FILE_NAME, AppConfig.PREFER_COOKIE_TAG, "");
                if(!TextUtils.isEmpty(cookie))
                {
                }*//*
                //MyLog.e("user-agent:" + headers.get("User-Agent") + "");
                return headers;
            }
        };
        // 为当前请求添加标记
        stringRequest.setTag(tag);
        // 设置超时时间
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(2 * 1000, 0, 1.0f));
        // 将当前请求添加到请求队列中
        MyApication.getRequestQueue().add(stringRequest);
        // 重启当前请求队列
//        MyApication.getRequestQueue().start();
    }

    *//*
    * 获取POST请求内容（请求的代码为Map）
    * 参数：
    * context：当前上下文；
    * url：请求的url地址；
    * tag：当前请求的标签；
    * params：POST请求内容；
    * volleyListenerInterface：VolleyListenerInterface接口；
    * *//*
    public static void RequestPost(String url, final Map<String, String> params, String tag, VolleyListenerInterface volleyListenerInterface) {
        // 清除请求队列中的tag标记请求
        MyApication.getRequestQueue().cancelAll(tag);
//         创建当前的POST请求，并将请求内容写入Map中
        stringRequest = new StringRequest(Request.Method.POST, url, volleyListenerInterface.responseListener(), volleyListenerInterface.errorListener()) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = super.getHeaders();
                if (headers == null || headers.equals(Collections.emptyMap())) {
                    headers = new HashMap<String, String>();
                }
               *//* Context context=AppManager.topActivity();
                if (context != null) {
                    StringBuilder label = new StringBuilder();
                    label.append(context.getApplicationInfo().loadLabel(context.getPackageManager()));
                    label.append("/");
                    try {

                        if(context==null)
                        {
                            return headers;
                        }
                        PackageInfo pInfo =context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
                        label.append(pInfo.versionName);
                    } catch (PackageManager.NameNotFoundException e) {
                    }
                    label.append(" ");
                    label.append(System.getProperty("http.agent"));*//*
                String userAgent = System.getProperty("http.agent");
                if (!StringUtils.isSpace(userAgent)) {
                    headers.put("User-Agent", userAgent + " JYC_App_" + SystemToolUtils.getAppVersionName(AppManager.topActivity()) + "_" + "android");
                }
               *//* String cookie=PreferenceHelper.readString(PreferenceHelper.DEFAULT_FILE_NAME,AppConfig.PREFER_COOKIE_TAG,"");
                if(!TextUtils.isEmpty(cookie))
                {
                }*//*
               // MyLog.e("user-agent:" + headers.get("User-Agent") + "");
                //}

                return headers;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                //MyLog.e("post_response_header===" + response.headers.toString());
                return super.parseNetworkResponse(response);
            }

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
               *//* params.put("access_token", PreferenceHelper.readString(PreferenceHelper.DEFAULT_FILE_NAME, AppConfig.PREFER_TOKEN_TAG, ""));
                params.put("appVersion",SystemToolUtils.getAppVersionName(AppManager.topActivity()));
                params.put("bundleID",SystemToolUtils.getAppPackageName(AppManager.topActivity()));*//*
                return params;
            }

         *//*   @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
               // return super.parseNetworkResponse(response);
                try {

                    Map<String, String> responseHeaders = response.headers;
                    String rawCookies = responseHeaders.get("Set-Cookie");
                    saveSettingNote(rawCookies);//保存Cookie
                    Log.i("px",rawCookies+"\n");
                    String dataString = new String(response.data, "UTF-8");
                    Log.i("px",dataString);
                    return Response.success(dataString, HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                }
            }*//*
        };
        // 为当前请求添加标记
        stringRequest.setTag(tag);
        //自定义超时时间
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, 1.0f));
//         将当前请求添加到请求队列中
        MyApication.getRequestQueue().add(stringRequest);
//         重启当前请求队列
//        MyApication.getRequestQueue().start();
    }

    *//**
     * 用于在post网络请求特别是登录请求获得cookie
     *
     * @param url
     * @param params
     * @param tag
     * @param volleyListenerInterface
     *//*
    public static void cookieRequestPost(String url, final Map<String, String> params, String tag, VolleyListenerInterface volleyListenerInterface) {
        // 清除请求队列中的tag标记请求
        MyApication.getRequestQueue().cancelAll(tag);
//         创建当前的POST请求，并将请求内容写入Map中
        stringRequest = new StringRequest(Request.Method.POST, url, volleyListenerInterface.responseListener(), volleyListenerInterface.errorListener()) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                params.put("access_token", PreferenceHelper.readString(PreferenceHelper.DEFAULT_FILE_NAME, AppConfig.PREFER_TOKEN_TAG, ""));
                params.put("appVersion",SystemToolUtils.getAppVersionName(AppManager.topActivity()));
                params.put("bundleID",SystemToolUtils.getAppPackageName(AppManager.topActivity()));
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = super.getHeaders();
                if (headers == null || headers.equals(Collections.emptyMap())) {
                    headers = new HashMap<String, String>();
                }
                String userAgent = System.getProperty("http.agent");
                if (!StringUtils.isSpace(userAgent)) {
                    headers.put("User-Agent", userAgent + " JYC_App_" + SystemToolUtils.getAppVersionName(AppManager.topActivity()) + "_" + "android");
                }
                //MyLog.e("user-agent:" + headers.get("User-Agent") + "");
                return headers;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                // return super.parseNetworkResponse(response);
                Map<String, String> responseHeaders = response.headers;
                String rawCookies = responseHeaders.get("Set-Cookie");
                saveSettingNote(rawCookies);//保存Cookie
                return super.parseNetworkResponse(response);
            }
        };
        // 为当前请求添加标记
        stringRequest.setTag(tag);
        //自定义超时时间
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, 1.0f));
//         将当前请求添加到请求队列中
        MyApication.getRequestQueue().add(stringRequest);
//         重启当前请求队列
//        MyApication.getRequestQueue().start();
    }

    public static void saveSettingNote(String cookie) {
        if (cookie != null && !TextUtils.isEmpty(cookie)) {
            try {
                //MyLog.e("cookie=====" + cookie);
                PreferenceHelper.write(PreferenceHelper.DEFAULT_FILE_NAME, AppConfig.PREFER_COOKIE_TAG, cookie);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                PreferenceHelper.write(PreferenceHelper.DEFAULT_FILE_NAME, AppConfig.PREFER_COOKIE_TAG, "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public static void RequestPost(String url, String tag, VolleyListenerInterface volleyListenerInterface) {
        // 清除请求队列中的tag标记请求
        MyApication.getRequestQueue().cancelAll(tag);
//         创建当前的POST请求，并将请求内容写入Map中
        stringRequest = new StringRequest(Request.Method.POST, url, volleyListenerInterface.responseListener(), volleyListenerInterface.errorListener()) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = super.getHeaders();
                if (headers == null || headers.equals(Collections.emptyMap())) {
                    headers = new HashMap<String, String>();
                }
                String userAgent = System.getProperty("http.agent");
                if (!StringUtils.isSpace(userAgent)) {
                    headers.put("User-Agent", userAgent + " JYC_App_" + SystemToolUtils.getAppVersionName(AppManager.topActivity()) + "_" + "android");
                }
               *//* String cookie=PreferenceHelper.readString(PreferenceHelper.DEFAULT_FILE_NAME, AppConfig.PREFER_COOKIE_TAG, "");
                if(!TextUtils.isEmpty(cookie))
                {
                }*//*
                //MyLog.e("user-agent:" + headers.get("User-Agent") + "");
                return headers;
            }
        };
        // 为当前请求添加标记
        stringRequest.setTag(tag);
        //自定义超时时间
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, 1.0f));
//         将当前请求添加到请求队列中
        MyApication.getRequestQueue().add(stringRequest);
//         重启当前请求队列
//        MyApication.getRequestQueue().start();
    }*/
}
